package com.xinchuang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinchuang.comment.KeyWord;
import com.xinchuang.comment.R;
import com.xinchuang.comment.ResultCode;
import com.xinchuang.entity.api.OaUserParam;
import com.xinchuang.entity.api.UserApi;
import com.xinchuang.mapper.OaUserMapper;
import com.xinchuang.mapper.UserApiMapper;
import com.xinchuang.service.LoginService;
import com.xinchuang.service.OaUserService;
import com.xinchuang.service.apiutil.impl.ApiUtilServiceImpl;
import com.xinchuang.utils.MyUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${isDev}")
    private boolean isDev;

    private final KeyWord keyWord;
    private final UserApiMapper userApiMapper;
    private final OaUserService oaUserService;

    @Override
    public String login(JSONObject jsonObject) {
        //jsonobject解析获取用户名
        String username = jsonObject.getString("username");
        //jsonobject解析获取密码
        String password = jsonObject.getString("password");
        try {
            if (!isDev) {
                HttpResponse login = ApiUtilServiceImpl.login(keyWord.getApi());
                if (login.getStatus() != HttpStatus.HTTP_OK) {
                    return JSON.toJSONString(R.fail(login.getStatus(), login.body()));
                }
                String verityToken = login.body();
                log.info("调用OA系统进行登录时获取登录token:{}", verityToken);


                //调用OA 系统 进行登录
                log.info("调用OA系统进行登录参数：{}", jsonObject.toJSONString());
                HttpResponse execute = ApiUtilServiceImpl.doPost(keyWord.getApi() + ApiUtilServiceImpl.USER_LOGIN, jsonObject, verityToken);
                log.info("调用OA系统进行登录,返回状态：{}", execute.getStatus());
                log.info("调用OA系统进行登录,返回参数：{}", execute.body());
                if (execute.getStatus() != HttpStatus.HTTP_OK) {
                    log.error("登录获取用户异常：{}", execute.getStatus() + "," + execute.body());
                    return JSON.toJSONString(R.fail(500, "用户不存在，请联系管理员处理！"));
                }
                //将用户信息入库，供业务功能使用
                //返回的id是 expressId ！！！！！！
                JSONObject executeJson = JSONObject.parseObject(execute.body());
                //封装 oaUserParam
                OaUserParam oaUserParam = processOaUserParam(executeJson.getInteger("id"));
                if (Objects.isNull(oaUserParam)) {
                    return JSON.toJSONString(R.fail(500, "用户不存在，请联系管理员处理！"));
                }
                //封装 userApi
                UserApi userApi = processUserApi(executeJson, oaUserParam);

                JSONObject json = new JSONObject();
                json.put("id", userApi.getUserId() + "");
                json.put("name", userApi.getName());
                json.put("userName", userApi.getUsername());
                json.put("token", userApi.getToken());
                json.put("operations", JSONArray.parseArray(userApi.getOperationList()));
                json.put("routes", JSONArray.parseArray(userApi.getRoleList()));
                return JSON.toJSONString(R.data(json, "登录成功"));
            }else{
                UserApi userApi = userApiMapper.selectOne(new LambdaQueryWrapper<UserApi>().eq(UserApi::getUsername, username));
                JSONObject json = new JSONObject();
                json.put("id", userApi.getUserId() + "");
                json.put("name", userApi.getName());
                json.put("userName", userApi.getUsername());
                json.put("token", userApi.getToken());
                json.put("operations", JSONArray.parseArray(userApi.getOperationList()));
                json.put("routes", JSONArray.parseArray(userApi.getRoleList()));
                return JSON.toJSONString(R.data(json, "登录成功"));
            }
        } catch (Exception e) {
            log.error("登录异常：{}", e.toString(), e);
            return JSON.toJSONString(R.fail(ResultCode.REQ_REJECT.getCode(), "请返回原系统登录！"));
        }
    }

    /**
     * 封装 userApi
     *
     * @param userInfo
     * @param oaUserParam
     * @return
     */
    private UserApi processUserApi(JSONObject userInfo, OaUserParam oaUserParam) {
        UserApi api = userApiMapper.selectOne(new LambdaQueryWrapper<UserApi>().eq(UserApi::getId, oaUserParam.getId()));
        if (ObjectUtil.isNotNull(api)) {
            api.setId(oaUserParam.getId());
            api.setName(userInfo.getString("name"));
            api.setToken(userInfo.getString("token"));
            api.setUsername(userInfo.getString("username"));
            api.setDepartment(userInfo.getString("department"));
            api.setIsActive(userInfo.getBoolean("isActive"));
            api.setRoleList(userInfo.getJSONArray("roles").toJSONString());
            api.setOperationList(userInfo.getJSONArray("operations").toJSONString());
            userApiMapper.updateById(api);
            return api;
        } else {
            UserApi userApi = new UserApi();
            userApi.setId(oaUserParam.getId());
            userApi.setName(userInfo.getString("name"));
            userApi.setToken(userInfo.getString("token"));
            userApi.setUsername(userInfo.getString("username"));
            userApi.setDepartment(userInfo.getString("department"));
            userApi.setIsActive(userInfo.getBoolean("isActive"));
            userApi.setRoleList(userInfo.getJSONArray("roles").toJSONString());
            userApi.setOperationList(userInfo.getJSONArray("operations").toJSONString());
            userApiMapper.insert(userApi);
            return userApi;
        }
    }

    /**
     * 封装 oaUserParam
     *
     * @param expressId
     * @return
     */
    private OaUserParam processOaUserParam(Integer expressId) {

        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, keyWord.getApi() + ApiUtilServiceImpl.VERITY_USER + expressId).timeout(1000 * 60 * 3).execute();
        if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
            log.error("登录校验时获取用户异常：{}", httpResponse.getStatus() + "," + httpResponse.body());
            return null;
        }
        JSONObject userInfo = JSONObject.parseObject(httpResponse.body());
        OaUserParam oaUserParam = new OaUserParam();
        oaUserParam.setId(userInfo.getInteger("id"));
        oaUserParam.setName(userInfo.getString("name"));
        oaUserParam.setUsername(userInfo.getString("username"));
        oaUserParam.setExpressId(userInfo.getInteger("expressId"));
        oaUserParam.setExpressUsername(userInfo.getString("expressUsername"));
        oaUserParam.setNemId(userInfo.getInteger("nemId"));
        oaUserParam.setNemUsername(userInfo.getString("nemUsername"));
        oaUserParam.setOaId(userInfo.getLong("oaId"));
        oaUserParam.setOaUsername(userInfo.getString("oaUsername"));
        oaUserParam.setIsActive(userInfo.getBoolean("isActive"));
        oaUserService.saveOrUpdate(oaUserParam);

        return oaUserParam;
    }

}
